package com.infore.statisticsAndAlarm.service.impl;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.infore.statisticsAndAlarm.constant.Constants;
import com.infore.statisticsAndAlarm.dto.WaterInstructionsDataDto;
import com.infore.statisticsAndAlarm.enums.ResultStatus;
import com.infore.statisticsAndAlarm.enums.WaterQualityTargetLevel;
import com.infore.statisticsAndAlarm.externalInterface.IDataReceivingService;
import com.infore.statisticsAndAlarm.externalInterface.IStieMangementService;
import com.infore.statisticsAndAlarm.outsideEntity.Project;
import com.infore.statisticsAndAlarm.repository.IDayDataRepository;
import com.infore.statisticsAndAlarm.repository.IMonthDataRepository;
import com.infore.statisticsAndAlarm.select.util.PageObject;
import com.infore.statisticsAndAlarm.service.IComparisonQualityService;
import com.infore.statisticsAndAlarm.util.CookiesUtil;
import com.infore.statisticsAndAlarm.util.DateUtil;
import com.infore.statisticsAndAlarm.util.MyBeanUtils;
import com.infore.statisticsAndAlarm.util.ObjectMapperUtil;
import com.infore.statisticsAndAlarm.util.Page;
import com.infore.statisticsAndAlarm.util.PageUtil;
import com.infore.statisticsAndAlarm.util.ReflexUtil;
import com.infore.statisticsAndAlarm.util.ResultEntity;
import com.infore.statisticsAndAlarm.util.WaterLevelUtils;
import com.infore.statisticsAndAlarm.util.WaterQualityUtil;
import com.infore.statisticsAndAlarm.vo.ChartsVo;

@Service
public class ComparisonQualityServiceImpl implements IComparisonQualityService {

	@Autowired
	private IDayDataRepository iDayDataRepository;
	@Autowired
	private IStieMangementService iStieMangementService;
	@Autowired
	private ObjectMapperUtil ObjectMapperUtil;
	@Autowired
	private IDataReceivingService iDataReceivingService;
	@Autowired
	private IMonthDataRepository iMonthDataRepository;
	@Autowired
	private WaterLevelUtils WaterLevelUtils;
	
	/**根据区域流域的到站点mn**/
	List<String> getStationMns(HttpServletRequest request,String queryCode, String queryType){
		List<String> mnList = new ArrayList<String>();
		if (!"station".equals(queryType)) {// 区分是按区域流域查询，还是单站点查询
			// 得到站点信息
			String platfrom = CookiesUtil.getCookieValue(request, "platformId");
			String appCode = CookiesUtil.getCookieValue(request, "appCode");
			String userId = CookiesUtil.getCookieValue(request, "userId");
			String admin = CookiesUtil.getCookieValue(request, "admin");
			List<Map<String, Object>> stationList = new ArrayList<Map<String, Object>>();
			ResultEntity stationResultEntity = iStieMangementService.queryStationInfoByCodes(
					queryCode, queryType, userId,platfrom, appCode, admin);
			if (stationResultEntity.getCode() == 0) {
				stationList = ObjectMapperUtil.getMapList(stationResultEntity);
				if (stationList == null || stationList.size() == 0) {
					return null;
				}
			}
			mnList = stationList.stream().map(l -> l.get("MN").toString()).collect(Collectors.toList());
		} else {
			mnList.add(queryCode);
		}
		return mnList;
	}
	
	// 获取数据接口----分组得到数据
	public List<Map<String, Object>> datasCenter(String timeType, String nativeTime, String compareTime,
			String queryCode, String queryType,HttpServletRequest request) {
		String time = nativeTime;
		List<Map<String, Object>> dataResult = new ArrayList<Map<String, Object>>();// 小时天月数据结果集
		List<String> mnList = new ArrayList<String>();
		mnList = getStationMns(request, queryCode, queryType);
		if (mnList == null || mnList.size() == 0) {
			return dataResult;
		}
		String stationMn = StringUtils.join(mnList, ",");
		// 查询单站点下因子code集合
		ResultEntity projectCodesEntity = iStieMangementService.queryProjectByStationMn(stationMn);
		List<String> projectCodes = ObjectMapperUtil.convertList(projectCodesEntity, String.class);// 站点下因子集合
		if (projectCodes == null || projectCodes.size() == 0) {
			return dataResult;
		}
		String startTime = "";
		String endTime = "";
		String pattern = "";
		// 按时间分发给不同的接口查询，并设置起止时间
		if ("day".equals(timeType)) {
			startTime = time + " 00:00:00";
			endTime = time + " 23:59:59";
			pattern = DateUtil.DATE_SMALL_YMDHH;// 时间转换格式，天要查小时表
			String codeString = StringUtils.join(projectCodes, ",");
			ResultEntity resultEntity = iDataReceivingService.audioMoreReport(stationMn, codeString, startTime,
					endTime);
			if (resultEntity.getCode() != 0) {
				return dataResult;
			}
			dataResult = ObjectMapperUtil.convertListMap(resultEntity);
		} else if ("month".equals(timeType)) {
			startTime = time + "-01";
			pattern = DateUtil.DATE_SMALL_STR;// 时间转换格式，月要查当月下的天表
			Date endDate1 = DateUtil.stringToDate(time, DateUtil.DATE_SMALL_YM);
			endTime = DateUtil.getLastDayM(endDate1, pattern);// 得到当月最后一天
			Date startDate = DateUtil.stringToDate(startTime, pattern);
			Date endDate = DateUtil.stringToDate(endTime, pattern);
			dataResult = iDayDataRepository.audioMoreReport(startDate, endDate, projectCodes, mnList);
		} else {
			pattern = DateUtil.DATE_SMALL_YM;// 时间转换格式
			startTime = time + "-01";
			endTime = time + "-12";
			Date startDate = DateUtil.stringToDate(startTime, pattern);
			Date endDate = DateUtil.stringToDate(endTime, pattern);
			dataResult = iMonthDataRepository.audioMoreReport(startDate, endDate, projectCodes, mnList);
		}
		return dataResult;
	}

	@SuppressWarnings("unchecked")
	public ResultEntity moreProjectDetailsReports(String timeType, String nativeTime, String compareTime,
			String queryCode, String queryType,HttpServletRequest request) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();// 最终返回结果集
		// 得到本期数据
		List<Map<String, Object>> dataResult = datasCenter(timeType, nativeTime, 
				compareTime, queryCode, queryType, request);
		Map<String, List<Map<String, Object>>> dataResults = new HashMap<String, List<Map<String, Object>>>();
		dataResults.put(nativeTime, dataResult);
		// 得到对比期数据
		List<Map<String, Object>> dataResultCompare = datasCenter(timeType, compareTime, nativeTime, queryCode,
				queryType, request);
		dataResults.put(compareTime, dataResultCompare);
		if ((dataResult == null || dataResult.size() == 0)
				&& (dataResultCompare == null || dataResultCompare.size() == 0)) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		// 遍历设置值---因为返回的是因子的值，所以先按照因子进行分组，然后再计算平均值
		dataResults.forEach((k, Klist) -> {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("time", k);
			Map<String, List<Map<String, Object>>> groupList = Klist.stream()
					.collect(Collectors.groupingBy(l -> l.get("CODE").toString()));
			groupList.forEach((g, glist) -> {
				Double avgValue = glist.stream()
						.collect(Collectors.averagingDouble(m -> Double.parseDouble(m.get("VALUE").toString())));
				String value = String.format("%.3f", avgValue);
				dataMap.put(g, value);
			});
			// 将本期数值放在首位
			if (k.equals(nativeTime)) {
				list.add(0, dataMap);
			} else {
				list.add(dataMap);
			}
		});
		// 获得因子信息
		List<String> mns = getStationMns(request, queryCode, queryType);
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mns);
		Map<String, Project> projectMap = null;
		if (projectResultEntity.getCode() == 0) {
			projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent()).get("info");
		}
		List<Map<String, Object>> projectTotaList = new ArrayList<Map<String, Object>>();
		if (projectMap != null) {
			for (Entry<String, Project> projectCode : projectMap.entrySet()) {
				Project project = MyBeanUtils
						.convertMapToBean((Map<String, Object>) projectMap.get(projectCode.getKey()), Project.class);
				Map<String, Object> projectMapList = new HashMap<String, Object>();
				projectMapList.put("unit", project.getProjectUnit());// 因子单位
				projectMapList.put("code", project.getProjectCode());// 因子编码
				projectMapList.put("name", project.getProjectName());// 因子名称
				projectTotaList.add(projectMapList);
			}
		}
		List<String> projectCodes = new ArrayList<String>(projectMap.keySet());
		for (String code : projectCodes) {
			for (Map<String, Object> map : list) {
				if (!map.containsKey(code)) {
					map.put(code, "");
				}
			}
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list)
				.setInfo(projectTotaList);
	}

	@SuppressWarnings("unchecked")
	public ResultEntity moreWaterQualityBars(String timeType, String nativeTime, String compareTime, String queryCode,
			String queryType,HttpServletRequest request) {
		ChartsVo chartsVo = new ChartsVo();
		List<String> xAxis = new ArrayList<String>();
		List<Map<String, Object>> series = new ArrayList<Map<String, Object>>();
		Map<String, Object> seriesMap = new HashMap<String, Object>();
		Map<String, Object> seriesMapCompare = new HashMap<String, Object>();
		List<Integer> data = new ArrayList<Integer>();
		List<Integer> dataCompare = new ArrayList<Integer>();
		// 得到本期数据
		List<Map<String, Object>> dataResult = datasCenter(timeType, nativeTime, compareTime,
				queryCode, queryType, request);
		Map<String, List<Map<String, Object>>> dataResults = new HashMap<String, List<Map<String, Object>>>();
		dataResults.put(nativeTime, dataResult);
		// 得到对比期数据
		List<Map<String, Object>> dataResultCompare = datasCenter(timeType, compareTime, nativeTime, queryCode,
				queryType, request);
		dataResults.put(compareTime, dataResultCompare);
		if ((dataResult == null || dataResult.size() == 0)
				&& (dataResultCompare == null || dataResultCompare.size() == 0)) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		List<String> mns = getStationMns(request, queryCode, queryType);
		// 得到所有因子
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mns);
		Map<String, Project> projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity
				.getContent()).get("info");
		for (Entry<String, Project> projectCode : projectMap.entrySet()) {
			// 因子
			Project project = MyBeanUtils.convertMapToBean((Map<String, Object>) projectMap.get(projectCode.getKey()),
					Project.class);
			xAxis.add(project.getProjectName());// 设置横坐标
			data.add(null);// 本期值和对比值设置全为null
			dataCompare.add(null);
		}
		seriesMap.put("name", nativeTime);
		seriesMap.put("data", data);
		seriesMapCompare.put("name", compareTime);
		seriesMapCompare.put("data", dataCompare);
		series.add(seriesMap);
		series.add(seriesMapCompare);
		// 计算水质等级集合
		List<WaterInstructionsDataDto> dtoList = new ArrayList<WaterInstructionsDataDto>();
		dataResults.forEach((k, klist) -> {
			// 得到某一时间的数据集合，然后按照因子编码分组
			Map<String, List<Map<String, Object>>> groupList = klist.stream()
					.collect(Collectors.groupingBy(l -> l.get("CODE").toString()));
			groupList.forEach((g, glist) -> {
				if (projectResultEntity.getCode() == 0) {
					Project project = MyBeanUtils.convertMapToBean((Map<String, Object>) projectMap.get(g),
							Project.class);
					String name = project.getProjectName();
					String projectCode = project.getProjectCode();
					// 如果横轴集合中含有当前因子的名称，根据集合下标，用现有的因子等级替换掉原来的null
					if (xAxis.contains(name)) {
						Double value = glist.stream().collect(
								Collectors.averagingDouble(l -> Double.parseDouble(l.get("VALUE").toString())));// 当前因子的平均值
						WaterInstructionsDataDto dto = new WaterInstructionsDataDto();
						ReflexUtil.setValue(dto, WaterInstructionsDataDto.class, projectCode, String.class,
								value.toString());
						dtoList.add(dto);
						WaterQualityUtil.setWaterQuality(dtoList);
						String level = dto.getWaterQuality();// 实际水质等级
						int index = xAxis.indexOf(name);
						if (k.equals(nativeTime)) {
							data.remove(index);
							data.add(index, Integer.parseInt(level));
						} else {
							dataCompare.add(index, Integer.parseInt(level));
						}
					}
				}
			});
		});
		chartsVo.setxAxis(xAxis);
		chartsVo.setSeries(series);
		if (series == null || series.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(chartsVo);
	}

	@SuppressWarnings("unchecked")
	public ResultEntity moreWaterQualityPie(String timeType, String nativeTime, String compareTime, String queryCode,
			String queryType,HttpServletRequest request) {
		List<Object> singleSourceTime = new ArrayList<Object>();// 时间列
		List<List<Object>> sourceList = new ArrayList<List<Object>>();
		Map<String, Object> source = new HashMap<String, Object>();// 返回结果集
		Map<String, Object> list = new HashMap<String, Object>(0);// 分组处理结果集
		// 得到本期数据
		List<Map<String, Object>> dataResult = datasCenter(timeType, nativeTime, compareTime, queryCode, 
				queryType,request);
		Map<String, List<Map<String, Object>>> dataResults = new HashMap<String, List<Map<String, Object>>>();
		dataResults.put(nativeTime, dataResult);
		// 得到对比期数据
		List<Map<String, Object>> dataResultCompare = datasCenter(timeType, compareTime, nativeTime, queryCode,
				queryType,request);
		dataResults.put(compareTime, dataResultCompare);
		if ((dataResult == null || dataResult.size() == 0)
				&& (dataResultCompare == null || dataResultCompare.size() == 0)) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		// 计算水质等级集合
		List<WaterInstructionsDataDto> dtoList = new ArrayList<WaterInstructionsDataDto>();
		// 遍历设置值
		dataResults.forEach((k, Klist) -> {// 按本期和对比期循环遍历
			// 先创建一个默认值为0的空集合，在匹配更新
			List<Map<String, Object>> pieMapList = new ArrayList<Map<String, Object>>();
			for (WaterQualityTargetLevel e : WaterQualityTargetLevel.values()) {
				Map<String, Object> pieMap = new HashMap<String, Object>();
				if ("0".equals(e.getStatusCode()) || "1".equals(e.getStatusCode())) {
					continue;
				} else if ("2".equals(e.getStatusCode())) {
					pieMap.put("code", 12);
					pieMap.put("name", "I-II类");
					pieMap.put("value", 0);
					pieMapList.add(pieMap);
				} else {
					pieMap.put("code", e.getStatusCode());
					pieMap.put("name", e.getReasonPhrase());
					pieMap.put("value", 0);
					pieMapList.add(pieMap);
				}
			}
			// 得到某一时间的数据集合，然后按照mn号分组
			Map<String, List<Map<String, Object>>> groupList = Klist.stream()
					.collect(Collectors.groupingBy(x -> x.get("MN").toString()));
			// 总数
			groupList.forEach((m, mList) -> {// 遍历分组后的集合
				WaterInstructionsDataDto dto = new WaterInstructionsDataDto();
				mList.forEach(d -> {// 按照因子编码计算水质等级
					String projectCode = d.get("CODE").toString();
					String value = d.get("VALUE").toString();
					ReflexUtil.setValue(dto, WaterInstructionsDataDto.class, projectCode, String.class, value);
					dtoList.add(dto);
				});
				WaterQualityUtil.setWaterQuality(dtoList);
				String level = dto.getWaterQuality();// 实际水质等级
				for (Map<String, Object> map : pieMapList) {
					if (map.get("code").toString().contains(level)) {
						map.put("value", ((Integer) map.get("value")) + 1);
					}
				}
			});
			list.put(k, pieMapList);
		});
		// 拼接总结语句
		NumberFormat format = NumberFormat.getPercentInstance();
		format.setMaximumFractionDigits(2);// 设置保留几位小数
		String message = "";
		List<Map<String, Object>> summaryMap = (List<Map<String, Object>>) list.get(nativeTime);// 得到本期数据
		List<Map<String, Object>> summaryMapCompare = (List<Map<String, Object>>) list.get(compareTime);// 得到本期数据
		Double count = (summaryMap.stream().mapToInt(l -> (Integer) l.get("value")).sum()) / 1.0;// 得到对比期记录总数并返回double类型
		if (count > 0) {
			for (Map<String, Object> map : summaryMap) {
				String pct = format.format((Integer) map.get("value") / count);
				message = message + map.get("name").toString() + "占" + pct + ";";
			}
		}
		// 计算所占比例最大的水质等级
		List<Integer> cunCount = summaryMap.stream().map(l -> (Integer) l.get("value")).collect(Collectors.toList());// 得到最大记录
		Integer maxInteger = Collections.max(cunCount);
		int index = cunCount.indexOf(maxInteger);
		String waterQuality = WaterLevelUtils.calculateProject(summaryMap.get(index).get("name").toString());
		message = "结论：" + nativeTime + "总体" + waterQuality + ",其中：" + message;
		// 封装成两个饼图对比数据结构
		singleSourceTime.add("time");
		singleSourceTime.add(nativeTime);
		singleSourceTime.add(compareTime);
		sourceList.add(singleSourceTime);
		List<Object> nameList = summaryMap.stream().map(l -> l.get("name")).collect(Collectors.toList());// 得到所有时间集合
		List<Object> value = summaryMap.stream().map(l -> l.get("value")).collect(Collectors.toList());// 得到本期值
		List<Object> conpareValue = summaryMapCompare.stream().map(l -> l.get("value")).collect(Collectors.toList());// 得到对比期值
		// 设位置每个集合的的第一个值用来做名字
		for (int i = 0; i < 5; i++) {
			List<Object> singleSource = new ArrayList<Object>();
			singleSource.add(0, nameList.get(i));
			sourceList.add(singleSource);
		}
		// 设置每个集合除第一个的其他值
		for (int i = 1; i < 6; i++) {
			List<Object> sourceOne = sourceList.get(i);
			sourceOne.add(1, value.get(i - 1));
			sourceOne.add(2, conpareValue.get(i - 1));
		}
		source.put("source", sourceList);
		source.put("message", message);// 返回总结信息
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(source);
	}

	public ResultEntity moreWaterQualityBarsUpDown(String timeType, String nativeTime, String compareTime,
			String queryCode, String queryType,HttpServletRequest request) {
		ChartsVo chartsVo = new ChartsVo();
		List<String> xAxis = new ArrayList<String>();
		List<Map<String, Object>> series = new ArrayList<Map<String, Object>>();
		Map<String, Object> seriesMap = new HashMap<String, Object>();
		Map<String, Object> seriesMapCompare = new HashMap<String, Object>();
		List<Integer> data = new ArrayList<Integer>();
		List<Integer> dataCompare = new ArrayList<Integer>();
		for (WaterQualityTargetLevel e : WaterQualityTargetLevel.values()) {
			Map<String, Object> pieMap = new HashMap<String, Object>();
			if ("0".equals(e.getStatusCode()) || "1".equals(e.getStatusCode())) {
				continue;
			} else if ("2".equals(e.getStatusCode())) {
				pieMap.put("name", "I-II类");
				xAxis.add("I-II类");
				data.add(0);
				dataCompare.add(0);
			} else {
				xAxis.add(e.getReasonPhrase());
				data.add(0);
				dataCompare.add(0);
			}
		}
		seriesMap.put("native", data);
		seriesMapCompare.put("compare", dataCompare);
		series.add(seriesMap);
		series.add(seriesMapCompare);
		// 得到本期数据
		List<Map<String, Object>> dataResult = datasCenter(timeType, nativeTime, compareTime,
				queryCode, queryType,request);
		Map<String, List<Map<String, Object>>> dataResults = new HashMap<String, List<Map<String, Object>>>();
		if (dataResult != null && dataResult.size() > 0) {
			dataResults.put(nativeTime, dataResult);
		}
		// 得到对比期数据
		List<Map<String, Object>> dataResultCompare = datasCenter(timeType, compareTime, nativeTime, queryCode,
				queryType,request);
		if (dataResultCompare != null && dataResultCompare.size() > 0) {
			dataResults.put(compareTime, dataResultCompare);
		}
		if (dataResults == null || dataResults.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		// 本期和对比期站点数目
//		Map<String, Object> sumMn = new HashMap<String, Object>();
		// 计算水质等级集合
		List<WaterInstructionsDataDto> dtoList = new ArrayList<WaterInstructionsDataDto>();
		dataResults.forEach((k, klist) -> {
			if (klist.size() > 0) {
				// 得到某一时间的数据集合，然后按照mn号分组
				Map<String, List<Map<String, Object>>> groupList = klist.stream()
						.collect(Collectors.groupingBy(l -> l.get("MN").toString()));
//				sumMn.put(k, groupList.keySet().size());//保存站点数目
				groupList.forEach((m, mList) -> {// 遍历分组后的集合
					WaterInstructionsDataDto dto = new WaterInstructionsDataDto();
					mList.forEach(d -> {// 按照因子编码计算水质等级
						String projectCode = d.get("CODE").toString();
						String value = d.get("VALUE").toString();
						ReflexUtil.setValue(dto, WaterInstructionsDataDto.class, projectCode, String.class, value);
						dtoList.add(dto);
					});
					WaterQualityUtil.setWaterQuality(dtoList);
					String level = dto.getWaterQuality();// 实际水质等级
					if (StringUtils.isNotBlank(level)) {
						Integer levelInteger = Integer.parseInt(level);
						int flag = 2;// 用来判断1-2级时，确保放在集合的第一位
						if (levelInteger == 1) {
							flag = 1;
						}else if (levelInteger == 2) {
							flag = 2;
						}
						if (k.equals(nativeTime) && levelInteger > 0) {
							Integer oldLevel = data.get(levelInteger - flag) == null ? 0
									: data.get(levelInteger - flag);
							data.remove(levelInteger - flag);
							data.add(levelInteger - flag, oldLevel + 1);
						} else if (k.equals(compareTime) && levelInteger > 0) {
							Integer oldLevel = dataCompare.get(levelInteger - flag) == null ? 0
									: dataCompare.get(levelInteger - flag);
							dataCompare.remove(levelInteger - flag);
							dataCompare.add(levelInteger - flag, oldLevel + 1);
						}
					}
				});
			}
		});
		chartsVo.setxAxis(xAxis);
		chartsVo.setSeries(series);
		if (series == null || series.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(chartsVo);
	}

	@SuppressWarnings("unchecked")
	public ResultEntity projectOverNumberReports(String timeType, String nativeTime, String compareTime,
			String queryCode, String queryType ,HttpServletRequest request) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// 获得因子信息
		List<String> mns = getStationMns(request, queryCode, queryType);
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mns);// 得到所有因子信息
		Map<String, Project> projectMap = null;
		if (projectResultEntity.getCode() == 0) {
			projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent()).get("info");
		}
		Map<String, Object> projectMapList = new HashMap<String, Object>();// 本期返回数据值，初始默认为0
		Map<String, Object> projectMapCompare = new HashMap<String, Object>();// 对比期返回数据值，初始默认为0
		List<Map<String, Object>> projectTotaList = new ArrayList<Map<String, Object>>();
		if (projectMap != null) {// 遍历所有因子集合，来设置返回的数据结构
			for (Entry<String, Project> projectCode : projectMap.entrySet()) {
				Project project = MyBeanUtils
						.convertMapToBean((Map<String, Object>) projectMap.get(projectCode.getKey()), Project.class);
				projectMapList.put(project.getProjectCode(), 0);// 因子编码+因子值-本期
				// projectMapList.put(project.getProjectCode()+"name",
				// project.getProjectName());//因子编码+名称-本期
				projectMapCompare.put(project.getProjectCode(), 0);// 因子编码+因子值
				// projectMapCompare.put(project.getProjectCode()+"name",
				// project.getProjectName());//因子编码+名称
				// 返回因子表头
				Map<String, Object> projectTitle = new HashMap<String, Object>();
				projectTitle.put("unit", project.getProjectUnit());// 因子单位
				projectTitle.put("code", project.getProjectCode());// 因子编码
				projectTitle.put("name", project.getProjectName());// 因子名称
				projectTotaList.add(projectTitle);
			}
			projectMapList.put("time", nativeTime);// 本期时间
			projectMapList.put("dataName", "本期值");
			projectMapCompare.put("time", compareTime);
			projectMapCompare.put("dataName", "对比期值");
			list.add(projectMapList);// 添加本期和对比期到返回集list，先存本期
			list.add(projectMapCompare);
		}
		// 得到区域流域信息含目标等级
		ResultEntity resultEntity = iStieMangementService.queryAreaByAreaCode(queryCode, queryType);
		List<Map<String, Object>> areaInfos = ObjectMapperUtil.getMapList(resultEntity);
		if (areaInfos == null || areaInfos.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		Map<String, Object> areaInfo = areaInfos.get(0);// 取得流域或者区域信息
		String aimLevel = areaInfo.get("aimWaterLevel") == null ? "" : areaInfo.get("aimWaterLevel").toString();// 取得目标水质等级
		if (StringUtils.isNotBlank(aimLevel)) {
			// 将目标谁水质等级转化成数字
			Integer aimLevelInteger = Integer.parseInt(WaterLevelUtils.exchangeWaterLevelToNumber(aimLevel));
			// 得到本期数据
			List<Map<String, Object>> dataResult = datasCenter(timeType, nativeTime, compareTime, 
					queryCode, queryType, request);
			Map<String, List<Map<String, Object>>> dataResults = new HashMap<String, List<Map<String, Object>>>();
			if (dataResult != null && dataResult.size() > 0) {
				dataResults.put(nativeTime, dataResult);
			}
			// 得到对比期数据
			List<Map<String, Object>> dataResultCompare = datasCenter(timeType, compareTime, nativeTime, 
					queryCode,queryType, request);
			if (dataResultCompare != null && dataResultCompare.size() > 0) {
				dataResults.put(compareTime, dataResultCompare);
			}
			if (dataResults == null || dataResults.size() == 0) {
				return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
			}
			// 遍历结果集
			dataResults.forEach((k, klist) -> {
				// 按照因子进行分组,如果大于目标值，则超标数量加一
				Map<String, List<Map<String, Object>>> groupList = klist.stream()
						.collect(Collectors.groupingBy(l -> l.get("CODE").toString()));
				groupList.forEach((g, glist) -> {
					// 遍历分组后的每一条记录，如果因子大于目标值，说明有站点下当前因子超标，则超标数量加一
					glist.forEach(single -> {
						String value = single.get("VALUE") == null ? "0" : single.get("VALUE").toString();
						Integer level = WaterQualityUtil.getWaterLevel(g, value);
						if (level > aimLevelInteger) {
							// 来判断更新本期还是结果期的超标因子数量
							if (k.equals(nativeTime)) {
								Integer oldNumber = (Integer) projectMapList.get(g);// 旧的因子数量
								projectMapList.put(g, oldNumber + 1);// 设置新的因子数量在旧的上加一
							} else {
								Integer oldNumberCom = (Integer) projectMapCompare.get(g);
								projectMapCompare.put(g, oldNumberCom + 1);
							}
						}
					});
				});
			});
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list)
				.setInfo(projectTotaList);
	}

	@SuppressWarnings("unchecked")
	public ResultEntity projectOverNumberBar(String timeType, String nativeTime, String compareTime, String queryCode,
			String queryType ,HttpServletRequest request) {
		ChartsVo chartsVo = new ChartsVo();
		List<String> xAxis = new ArrayList<String>();
		List<Map<String, Object>> series = new ArrayList<Map<String, Object>>();
		Map<String, Object> seriesMap = new HashMap<String, Object>();
		Map<String, Object> seriesMapCompare = new HashMap<String, Object>();
		List<Integer> data = new ArrayList<Integer>();
		List<Integer> dataCompare = new ArrayList<Integer>();
		// 获得因子信息
		List<String> mns = getStationMns(request, queryCode, queryType);
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mns);// 得到所有因子信息
		Map<String, Project> projectMap = null;
		if (projectResultEntity.getCode() == 0) {
			projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent()).get("info");
		}
		if (projectMap != null) {// 遍历所有因子集合，来设置返回的数据结构
			for (Entry<String, Project> projectCode : projectMap.entrySet()) {
				Project project = MyBeanUtils
						.convertMapToBean((Map<String, Object>) projectMap.get(projectCode.getKey()), Project.class);
				xAxis.add(project.getProjectName());// 设置x轴集合
				data.add(0);// 初始化本期值集合
				dataCompare.add(0);// 初始化对比期值集合
			} // 封装echarts中的series
			seriesMap.put("name", "本期值");
			seriesMap.put("data", data);
			seriesMapCompare.put("name", "对比期");
			seriesMapCompare.put("data", dataCompare);
			series.add(seriesMap);
			series.add(seriesMapCompare);
		}
		// 得到区域流域信息含目标等级
		ResultEntity resultEntity = iStieMangementService.queryAreaByAreaCode(queryCode, queryType);
		List<Map<String, Object>> areaInfos = ObjectMapperUtil.getMapList(resultEntity);
		if (areaInfos == null || areaInfos.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		Map<String, Object> areaInfo = areaInfos.get(0);// 取得流域或者区域信息
		String aimLevel = areaInfo.get("aimWaterLevel") == null ? "" : areaInfo.get("aimWaterLevel").toString();// 取得目标水质等级
		if (StringUtils.isNotBlank(aimLevel)) {
			// 将目标谁水质等级转化成数字
			Integer aimLevelInteger = Integer.parseInt(WaterLevelUtils.exchangeWaterLevelToNumber(aimLevel));
			// 得到本期数据
			List<Map<String, Object>> dataResult = datasCenter(timeType, nativeTime, compareTime, 
					queryCode, queryType, request);
			Map<String, List<Map<String, Object>>> dataResults = new HashMap<String, List<Map<String, Object>>>();
			if (dataResult != null && dataResult.size() > 0) {
				dataResults.put(nativeTime, dataResult);
			}
			// 得到对比期数据
			List<Map<String, Object>> dataResultCompare = datasCenter(timeType, compareTime, nativeTime,
					queryCode,queryType, request);
			if (dataResultCompare != null && dataResultCompare.size() > 0) {
				dataResults.put(compareTime, dataResultCompare);
			}
			if (dataResults == null || dataResults.size() == 0) {
				return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
			}
			//
//			List<Map<String, Object>> projectInfo = new ArrayList<Map<String,Object>>();
			// 遍历结果集
			dataResults.forEach((k, klist) -> {
				// 按照因子进行分组,如果大于目标值，则超标数量加一
				Map<String, List<Map<String, Object>>> groupList = klist.stream()
						.collect(Collectors.groupingBy(l -> l.get("CODE").toString()));
				groupList.forEach((g, glist) -> {
					// 得到当前因子的名字
					Map<String, Project> project = null;
					if (projectResultEntity.getCode() == 0) {
						project = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent())
								.get("info");
					}
//					Map<String, Object> projectTitle = new HashMap<>();
					Project proj = MyBeanUtils.convertMapToBean((Map<String, Object>) project.get(g), Project.class);
					String name = proj.getProjectName() == null ? "" : proj.getProjectName();
//					String unit = proj.getProjectUnit();
//					String proCode = proj.getProjectCode();
//					projectTitle.put("name", name);//返回表头信息
//					projectTitle.put("unit", unit);
//					projectTitle.put("code", proCode);
//					projectInfo.add(projectTitle);
					// 遍历分组后的每一条记录，如果因子大于目标值，说明有站点下当前因子超标，则超标数量加一
					glist.forEach(single -> {
						String value = single.get("VALUE") == null ? "0" : single.get("VALUE").toString();
						Integer level = WaterQualityUtil.getWaterLevel(g, value);
						if (level > aimLevelInteger) {
							// 来判断更新本期还是结果期的超标因子数量
							Integer index = xAxis.indexOf(name);// 根据名字得到该因子在集合中的下标
							if (index != -1) {
								if (k.equals(nativeTime)) {
									Integer oldNumber = data.get(index);// 旧的因子数量
									data.remove(index);// 删除旧值
									data.add(index, oldNumber + 1);// 设置新值
								} else {
									Integer oldNumber = dataCompare.get(index);// 旧的因子数量
									dataCompare.remove(index);
									dataCompare.add(index, oldNumber + 1);
								}
							}
						}
					});
				});
			});
		}
		chartsVo.setxAxis(xAxis);
		chartsVo.setSeries(series);
		if (series == null || series.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(chartsVo);
	}

	@SuppressWarnings("unchecked")
	public ResultEntity moreProjectDetailsReportsMn(String timeType, String nativeTime, String compareTime,
			String queryCode, String queryType, PageObject pageObject ,HttpServletRequest request) {
		// 最后返回结果集
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();// 本期记录。包含浓度和水质
		Map<String, Object> resultMapCmpare = new HashMap<String, Object>();// 对比期记录。包含浓度和水质
		Map<String, Object> dataMap = new HashMap<String, Object>();// 浓度集本期
		dataMap.put("time", "本期值");
		Map<String, Object> qualityMap = new HashMap<String, Object>();// 水质集本期
		qualityMap.put("time", "本期值");
		Map<String, Object> dataMapCompare = new HashMap<String, Object>();// 浓度集对比
		dataMapCompare.put("time", "对比期值");
		Map<String, Object> qualityMapCompare = new HashMap<String, Object>();// 水质集对比
		qualityMapCompare.put("time", "对比期值");
		// 得到本期数据
		List<Map<String, Object>> dataResult = datasCenter(timeType, nativeTime, compareTime, queryCode, 
				queryType, request);
		Map<String, List<Map<String, Object>>> dataResults = new HashMap<String, List<Map<String, Object>>>();
		if (dataResult != null && dataResult.size() > 0) {
			dataResults.put(nativeTime, dataResult);
		}
		// 得到对比期数据
		List<Map<String, Object>> dataResultCompare = datasCenter(timeType, compareTime, nativeTime, queryCode,
				queryType, request);
		if (dataResultCompare != null && dataResultCompare.size() > 0) {
			dataResults.put(compareTime, dataResultCompare);
		}
		if (dataResultCompare == null && dataResult == null) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		//
		dataResults.forEach((k, klist) -> {
			Map<String, List<Map<String, Object>>> groupList = klist.stream()
					.collect(Collectors.groupingBy(l -> l.get("CODE").toString()));
			groupList.forEach((g, glist) -> {
				Double avgValue = glist.stream()
						.collect(Collectors.averagingDouble(m -> Double.parseDouble(m.get("VALUE").toString())));
				String level = WaterQualityUtil.getWaterLevel(g, String.format("%.3f", avgValue)) + "";
				String quality = WaterLevelUtils.exchangeWaterLevelToChinese(level);
				if (k.equals(nativeTime)) {
					dataMap.put(g, String.format("%.3f", avgValue));
					qualityMap.put(g, quality);
				} else {
					dataMapCompare.put(g, String.format("%.3f", avgValue));
					qualityMapCompare.put(g, quality);
				}
			});
			// 确保本期数据放到第一条
			if (k.equals(nativeTime)) {
				resultMap.put("mmol", dataMap);
				resultMap.put("waterQyulaty", qualityMap);
				list.add(0, resultMap);
			} else {
				resultMapCmpare.put("mmol", dataMapCompare);
				resultMapCmpare.put("waterQyulaty", qualityMapCompare);
				list.add(resultMapCmpare);
			}
		});
		// 返回表头因子信息
		List<Map<String, Object>> factorList = new ArrayList<Map<String, Object>>();
		List<String> mns = getStationMns(request, queryCode, queryType);
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mns);
		Map<String, Project> projectMap = null;
		if (projectResultEntity.getCode() == 0) {
			projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent()).get("info");
			ResultEntity projectCodesEntity = iStieMangementService.queryProjectByStationMn(queryCode);
			List<String> projectCodes = ObjectMapperUtil.convertList(projectCodesEntity, String.class);// 站点下因子集合
			for (String string : projectCodes) {
				Project project = MyBeanUtils.convertMapToBean((Map<String, Object>) projectMap.get(string),
						Project.class);
				Map<String, Object> factor = new HashMap<String, Object>();
				factor.put("code", project.getProjectCode());
				factor.put("name", project.getProjectName());
				factor.put("unit", project.getProjectUnit());
				factorList.add(factor);
			}
		}
		// 分页设置
		if (pageObject != null && pageObject.getPageNumber() != null && pageObject.getPageSize() != null) {
			Page<Map<String, Object>> page = PageUtil.inventedPage(list, pageObject);
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setPage(page);
		} else {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list)
					.setInfo(factorList);
		}
	}

	@SuppressWarnings({ "unchecked", "unused" })
	public ResultEntity projectReportsCompareMn(String timeType, String nativeTime, String compareTime,
			String queryCode, String queryType, PageObject pageObject ,HttpServletRequest request) {
		// 最后返回结果集
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// 得到本期数据
		List<Map<String, Object>> dataResult = datasCenter(timeType, nativeTime, compareTime, queryCode,
				queryType, request);
		Map<String, List<Map<String, Object>>> dataResults = new HashMap<String, List<Map<String, Object>>>();
		if (dataResult != null && dataResult.size() > 0) {
			dataResults.put(nativeTime, dataResult);
		}
		// 得到对比期数据
		List<Map<String, Object>> dataResultCompare = datasCenter(timeType, compareTime, nativeTime, queryCode,
				queryType, request);
		if (dataResultCompare != null && dataResultCompare.size() > 0) {
			dataResults.put(compareTime, dataResultCompare);
		}
		if (dataResults == null && dataResultCompare == null) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		// 获得因子信息
		List<String> mns = getStationMns(request, queryCode, queryType);
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mns);// 得到所有因子信息
		Map<String, Project> projectMap = null;
		if (projectResultEntity.getCode() == 0) {
			projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent()).get("info");
			// 查询单站点下因子code集合
			ResultEntity projectCodesEntity = iStieMangementService.queryProjectByStationMn(queryCode);
			List<String> projectCodes = ObjectMapperUtil.convertList(projectCodesEntity, String.class);// 站点下因子集合
			for (String code : projectCodes) {
				if (projectMap != null) {
					Project proj = MyBeanUtils.convertMapToBean((Map<String, Object>) projectMap.get(code),
							Project.class);
					String name = proj.getProjectName();
					String unit = proj.getProjectUnit();
					Map<String, Object> dataMap = new HashMap<String, Object>();
					dataMap.put("code", code);
					dataMap.put("name", name);
					dataMap.put("unit", unit);
					dataMap.put("currentValue", "");
					dataMap.put("currentlevel", "");
					dataMap.put("compareValue", "");
					dataMap.put("comparelevel", "");
					dataMap.put("trend", "");
					list.add(dataMap);
				}
			}
			//
			dataResults.forEach((k, klist) -> {
				Map<String, List<Map<String, Object>>> groupList = klist.stream()
						.collect(Collectors.groupingBy(l -> l.get("CODE").toString()));
				groupList.forEach((g, glist) -> {
					Double avgValue = glist.stream()
							.collect(Collectors.averagingDouble(m -> Double.parseDouble(m.get("VALUE").toString())));
					String level = WaterQualityUtil.getWaterLevel(g, String.format("%.3f", avgValue)) + "";
					Integer index = projectCodes.indexOf(g);
					if (index > -1) {
						Map<String, Object> singleData = list.get(index);
						if (k.equals(nativeTime)) {
							singleData.put("currentValue", String.format("%.3f", avgValue));
							singleData.put("currentlevel", WaterLevelUtils.exchangeWaterLevelToChinese(level));
						} else {
							singleData.put("compareValue", String.format("%.3f", avgValue));
							singleData.put("comparelevel", WaterLevelUtils.exchangeWaterLevelToChinese(level));
						}
						if (!"".equals(singleData.get("currentlevel"))
								&& !"".equals(singleData.get(singleData.get("comparelevel")))) {
							Integer currentlevel = Integer.parseInt(
									WaterLevelUtils.exchangeWaterLevelToNumber(singleData.get("currentlevel") + ""));
							Integer comparelevel = Integer.parseInt(
									WaterLevelUtils.exchangeWaterLevelToNumber(singleData.get("comparelevel") + ""));
							singleData.put("trend", currentlevel - comparelevel);
						}
					}
				});
			});
		}
		if (pageObject != null && pageObject.getPageNumber() != null && pageObject.getPageSize() != null) {
			Page<Map<String, Object>> page = PageUtil.inventedPage(list, pageObject);
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setPage(page);
		} else {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
		}
	}

	public ResultEntity projectSummaryMn(String timeType, String nativeTime, String compareTime, String queryCode,
			String queryType, PageObject pageObject ,HttpServletRequest request) {
		// 最后返回结果集
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> dataCompare = new HashMap<String, Object>();
		// 得到本期数据
		List<Map<String, Object>> dataResult = datasCenter(timeType, nativeTime, compareTime, queryCode, 
				queryType, request);
		Map<String, List<Map<String, Object>>> dataResults = new HashMap<String, List<Map<String, Object>>>();
		if (dataResult != null && dataResult.size() > 0) {
			dataResults.put(nativeTime, dataResult);
		}
		// 得到对比期数据
		List<Map<String, Object>> dataResultCompare = datasCenter(timeType, compareTime, nativeTime, queryCode,
				queryType, request);
		if (dataResultCompare != null && dataResultCompare.size() > 0) {
			dataResults.put(compareTime, dataResultCompare);
		}
		if (dataResults == null || dataResults.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		List<WaterInstructionsDataDto> waterInstrList = new ArrayList<WaterInstructionsDataDto>();
		dataResults.forEach((k, klist) -> {
			WaterInstructionsDataDto waterInstr = new WaterInstructionsDataDto();
			Map<String, List<Map<String, Object>>> groupList = klist.stream()
					.collect(Collectors.groupingBy(l -> l.get("CODE").toString()));
			groupList.forEach((g, glist) -> {
				Double avgValue = glist.stream()
						.collect(Collectors.averagingDouble(m -> Double.parseDouble(m.get("VALUE").toString())));
				ReflexUtil.setValue(waterInstr, WaterInstructionsDataDto.class, g, String.class, avgValue.toString());
				waterInstrList.add(waterInstr);
			});
			WaterQualityUtil.setWaterQuality(waterInstrList);
			String level = waterInstr.getWaterQuality();
			if (k.equals(nativeTime)) {
				data.put("levelNum", level);
				data.put("level", WaterLevelUtils.exchangeWaterLevelToChinese(level));
				data.put("time", k);
			} else {
				dataCompare.put("levelNum", level);
				dataCompare.put("level", WaterLevelUtils.exchangeWaterLevelToChinese(level));
				dataCompare.put("time", k);
			}
		});
		String dataLevel = data.get("level") == null ? "" : data.get("level").toString();
		String dataLevelCompare = dataCompare.get("level") == null ? "" : data.get("level").toString();
		String message = "";
		// nativeTime+"为"+dataLevel+";"+compareTime+"为"+dataLevelCompare+";";
		if (StringUtils.isNotBlank(dataLevel) && StringUtils.isNotBlank(dataLevelCompare)) {
			Integer dataInteger = Integer.parseInt(WaterLevelUtils.exchangeWaterLevelToNumber(dataLevel));
			Integer dataCompareInteger = Integer.parseInt(WaterLevelUtils.exchangeWaterLevelToNumber(dataLevelCompare));
			if (dataInteger > dataCompareInteger) {
				message = message + "水质呈好转趋势";
			} else if (dataInteger == dataCompareInteger) {
				message = message + "水质持平";
			} else {
				message = message + "水质呈恶化趋势";
			}
		}
//		Map<String, Object> messageMap = new HashMap<String, Object>();
//		messageMap.put("message", message);
//		list.add(messageMap);
		list.add(data);
		list.add(dataCompare);
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list).setInfo(message);
	}
}
